package cn.maihe.elg.operation.supports.bank.service;

import cn.maihe.elg.operation.supports.bank.dto.*;
import cn.maihe.elg.operation.utils.ElgLogger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 中信银行Mock服务，用于测试时模拟银行接口响应
 */
@Service
@Slf4j
public class CiticBankMockService {

    /**
     * 生成模拟的账户明细响应数据
     */
    public CiticAccountDetailRespDTO generateMockAccountDetailResponse() {
        CiticAccountDetailRespDTO response = new CiticAccountDetailRespDTO();
        
        // 设置基本信息
        response.setStatus("AAAAAAA");
        response.setStatusText("交易处理成功");
        response.setAccountNo("1234567890123456789");
        response.setAccountName("泉州丰泽得兴融资担保有限公司");
        response.setOpenBankName("中信银行");
        response.setTotalRecords(3);
        response.setReturnRecords(3);
        
        // 生成模拟交易明细
        List<CiticAccountDetailItem> details = new ArrayList<>();
        
        // 交易1：保函费用收入
        CiticAccountDetailItem detail1 = new CiticAccountDetailItem();
        detail1.setTranDate(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")));
        detail1.setTranTime("143000");
        detail1.setTranNo("12345678901234");
        detail1.setSumTranNo("1234567890123");
        detail1.setTranAmount(BigDecimal.valueOf(1000.00));
        detail1.setCreditDebitFlag("C"); // 贷方，表示收入
        detail1.setOppAccountNo("9876543210987654321");
        detail1.setOppAccountName("测试客户A");
        detail1.setOppOpenBankName("招商银行");
        detail1.setAbstractText("保函费用-订单号:ORD20241201001");
        detail1.setCashTransferFlag("1"); // 转账
        detail1.setBalance(BigDecimal.valueOf(50000.00));
        detail1.setOriNum("ORI123456789");
        details.add(detail1);
        
        // 交易2：保函费用收入
        CiticAccountDetailItem detail2 = new CiticAccountDetailItem();
        detail2.setTranDate(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")));
        detail2.setTranTime("150000");
        detail2.setTranNo("12345678901235");
        detail2.setSumTranNo("1234567890124");
        detail2.setTranAmount(BigDecimal.valueOf(2000.00));
        detail2.setCreditDebitFlag("C"); // 贷方，表示收入
        detail2.setOppAccountNo("1111111111111111111");
        detail2.setOppAccountName("测试客户B");
        detail2.setOppOpenBankName("建设银行");
        detail2.setAbstractText("保函费用-订单号:ORD20241201002");
        detail2.setCashTransferFlag("1"); // 转账
        detail2.setBalance(BigDecimal.valueOf(52000.00));
        detail2.setOriNum("ORI123456790");
        details.add(detail2);
        
        // 交易3：手续费支出
        CiticAccountDetailItem detail3 = new CiticAccountDetailItem();
        detail3.setTranDate(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")));
        detail3.setTranTime("160000");
        detail3.setTranNo("12345678901236");
        detail3.setSumTranNo("1234567890125");
        detail3.setTranAmount(BigDecimal.valueOf(50.00));
        detail3.setCreditDebitFlag("D"); // 借方，表示支出
        detail3.setOppAccountNo("2222222222222222222");
        detail3.setOppAccountName("中信银行");
        detail3.setOppOpenBankName("中信银行");
        detail3.setAbstractText("手续费");
        detail3.setCashTransferFlag("1"); // 转账
        detail3.setBalance(BigDecimal.valueOf(51950.00));
        detail3.setOriNum("ORI123456791");
        details.add(detail3);
        
        response.setUserDataList(details);
        
        ElgLogger.info(log, l -> l.info("生成模拟账户明细数据，共{}条记录", details.size()));
        
        return response;
    }
    
    /**
     * 根据金额范围生成模拟数据
     */
    public CiticAccountDetailRespDTO generateMockAccountDetailResponseByAmount(BigDecimal lowAmount, BigDecimal upAmount) {
        CiticAccountDetailRespDTO response = generateMockAccountDetailResponse();
        
        if (lowAmount != null || upAmount != null) {
            List<CiticAccountDetailItem> filteredDetails = new ArrayList<>();
            
            for (CiticAccountDetailItem detail : response.getUserDataList()) {
                BigDecimal amount = new BigDecimal(String.valueOf(detail.getTranAmount()));
                
                boolean include = true;
                if (lowAmount != null && amount.compareTo(lowAmount) < 0) {
                    include = false;
                }
                if (upAmount != null && amount.compareTo(upAmount) > 0) {
                    include = false;
                }
                
                if (include) {
                    filteredDetails.add(detail);
                }
            }
            
            response.setUserDataList(filteredDetails);
            response.setTotalRecords(filteredDetails.size());
            response.setReturnRecords(filteredDetails.size());
            
            ElgLogger.info(log, l -> l.info("根据金额范围过滤后，共{}条记录", filteredDetails.size()));
        }
        
        return response;
    }
    
    /**
     * 生成错误响应
     */
    public CiticAccountDetailRespDTO generateErrorResponse(String errorCode, String errorMessage) {
        CiticAccountDetailRespDTO response = new CiticAccountDetailRespDTO();
        response.setStatus(errorCode);
        response.setStatusText(errorMessage);
        response.setTotalRecords(0);
        response.setReturnRecords(0);
        response.setUserDataList(new ArrayList<>());
        
        ElgLogger.info(log, l -> l.info("生成错误响应: {} - {}", errorCode, errorMessage));
        
        return response;
    }
    /**
     * @param request 开卡请求的 DTO，用于回显一些信息
     * @return 伪造的成功响应
     */
    public CiticCardOpenRespDTO generateMockCardOpenResponse(CiticCardOpenReqDTO request) {
        CiticCardOpenRespDTO response = new CiticCardOpenRespDTO();

        response.setStatus("AAAAAAA");
        response.setStatusText("交易处理成功");
        response.setStt("S2");
        response.setSetlcardNum(request.getSetlcardNum());
        response.setRelAcc(request.getAccountNo());

        String mockNewCardNo = "623280" + System.currentTimeMillis() % 10000000000L; // 模拟一个16位卡号
        response.setSetlcardNumNew(mockNewCardNo);

        ElgLogger.info(log, l -> l.info("MockService: 已生成模拟开卡成功响应，新卡号为: {}", mockNewCardNo));

        return response;
    }

    /**
     * @return 伪造的失败响应
     */
    public CiticCardOpenRespDTO generateMockCardOpenErrorResponse() {
        CiticCardOpenRespDTO response = new CiticCardOpenRespDTO();
        response.setStatus("AAAAAAA");
        response.setStatusText("交易处理成功");

        // 业务层面失败 (S1)
        response.setStt("S1");
        // 在 statusText 中可以放入更详细的业务失败原因
        response.setStatusText("模拟失败：模板卡状态异常");

        ElgLogger.info(log, l -> l.info("MockService: 已生成模拟开卡失败响应。"));
        return response;
    }
    /**
     * @param cardNo 被查询的卡号
     * @return 伪造的、包含流水列表的响应
     */
    public CiticCardDetailRespDTO generateMockCardDetailResponse(String cardNo) {
        CiticCardDetailRespDTO response = new CiticCardDetailRespDTO();
        response.setStatus("AAAAAAA");
        response.setStatusText("交易成功");
        response.setTotalRecords(2);
        response.setReturnRecords(2);

        List<CiticCardDetailItem> details = new ArrayList<>();
        CiticCardDetailItem item1 = new CiticCardDetailItem();
        item1.setOrderNum("MOCK_CARD_TXN_001");
        item1.setSetlcardNum(cardNo);
        item1.setTranDate(java.time.LocalDate.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd")));
        item1.setTranAmt(new java.math.BigDecimal("1234.56"));
        item1.setSetlCardDbCrFlag("C");
        item1.setHostTranDesc("模拟客户A付款");
        item1.setRelAcc("您的主账户号");
        item1.setCardholderNm("您的公司名");
        details.add(item1);

        // 模拟第二笔入账流水 (使用固定的流水号)
        CiticCardDetailItem item2 = new CiticCardDetailItem();
        item2.setOrderNum("MOCK_CARD_TXN_002");
        item2.setSetlcardNum(cardNo);
        item2.setTranDate(java.time.LocalDate.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd")));
        item2.setTranAmt(new java.math.BigDecimal("789.00"));
        item2.setSetlCardDbCrFlag("C");
        item2.setHostTranDesc("模拟客户B付款");
        item2.setRelAcc("您的主账户号");
        item2.setCardholderNm("您的公司名");
        details.add(item2);

        response.setUserDataList(details);

        ElgLogger.info(log, l -> l.info("MockService: 已为卡号 {} 生成 {} 条固定的模拟交易明细。", cardNo, details.size()));
        return response;
    }
}